import json
import os
import win32gui
import win32print
import win32con
import win32com.client
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QTextFormat, QColor
from PyQt5.QtWidgets import QWidget, QSystemTrayIcon, QAction, QMenu, QComboBox, QLineEdit, QFileDialog, QTextEdit
from PyQt5 import QtWidgets, QtCore, QtGui
from HandleTarget.handle_tool import handle_target_tool, set_global_handle, get_global_handle, format_code, \
    run_dome_tool
from utils.keyboard_event import set_run_dome_code


def get_real_resolution():
    """获取真实的分辨率"""
    hand = win32gui.GetDC(0)
    wide = win32print.GetDeviceCaps(hand, win32con.DESKTOPHORZRES)
    high = win32print.GetDeviceCaps(hand, win32con.DESKTOPVERTRES)
    return {"wide": wide, "high": high}


class MainIndexBody():
    def __init__(self, parent):
        self.main = parent
        self.setup_ui()
        self.format_code_result = "hello world"
        self.code_text = "hello world"

        timer = QtCore.QTimer()
        self.timer = timer

        self.bind_trigger()

    def setup_ui(self):
        # 左边布局
        self.left_layout_widget()
        # 右边布局
        self.right_layout_widget()
        # 右边顶部控件

    def left_layout_widget(self):
        self.horizontal_layoutt_widget = QtWidgets.QWidget(self.main)
        self.horizontal_layoutt_widget.setGeometry(QtCore.QRect(20, 10, 300, 780))
        self.horizontal_layout = QtWidgets.QHBoxLayout(self.horizontal_layoutt_widget)
        self.horizontal_layout.setContentsMargins(0, 0, 0, 0)

        # 实例化QComBox对象
        self.cb = QComboBox(self.horizontal_layoutt_widget)
        self.cb.setGeometry(QtCore.QRect(5, 15, 150, 30))

        # 多个添加条目
        self.cb.addItems(['Windows', 'Mac', 'Linux'])

        line_item = QLineEdit()
        line_item.setReadOnly(True)  # 设置只读
        line_item.setAlignment(Qt.AlignCenter)  # 设置文字居中
        self.cb.setLineEdit(line_item)

        # 信号
        self.cb.currentIndexChanged[str].connect(self.combo_box_event)  # 条目发生改变，发射信号，传递条目内容
        self.cb.currentIndexChanged[int].connect(self.combo_box_event)  # 条目发生改变，发射信号，传递条目索引

        # 小笔按钮
        self.pen_button = QtWidgets.QPushButton(self.horizontal_layoutt_widget)
        self.pen_button.setGeometry(QtCore.QRect(170, 15, 120, 30))
        self.pen_button.setText("抓 取")
        self.pen_button.clicked.connect(self.pen_target_event)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(os.getcwd() + "\\static\\icons\\broken_pencil.png"))
        self.pen_button.setIcon(icon1)

        self.bulletin_board_icon = QtWidgets.QLabel(self.horizontal_layoutt_widget)
        self.bulletin_board_icon.setGeometry(QtCore.QRect(5, 740, 150, 30))
        bulletin_board = QtGui.QPixmap(os.getcwd() + "\\static\\icons\\bulletin_board.png")
        self.bulletin_board_icon.setPixmap(bulletin_board)

        self.notice_text = QtWidgets.QLabel(self.horizontal_layoutt_widget)
        self.notice_text.setGeometry(QtCore.QRect(50, 740, 150, 30))
        self.notice_text.setText("欢迎使用抓取工具")

    def right_layout_widget(self):
        self.layout_widget = QtWidgets.QWidget(self.main)
        self.layout_widget.setGeometry(QtCore.QRect(369, 69, 1120, 720))
        self.vertical_layout = QtWidgets.QVBoxLayout(self.layout_widget)
        self.vertical_layout.setContentsMargins(0, 0, 0, 0)

        self.export_button = QtWidgets.QPushButton(self.main)
        self.export_button.setGeometry(QtCore.QRect(1330, 20, 111, 31))
        self.export_button.setText("导 出")
        self.export_button.setStyleSheet("color:rgb(30,30,30,255);font-size:18px;font-weight:bold:text")
        self.export_button.clicked.connect(self.export_file)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(os.getcwd() + "\\static\\icons\\down_loads.png"))
        self.export_button.setIcon(icon2)

        self.dome_button = QtWidgets.QPushButton(self.main)
        self.dome_button.setGeometry(QtCore.QRect(1170, 20, 111, 31))
        self.dome_button.setText("演 示")
        self.dome_button.setStyleSheet("color:rgb(30,30,30,255);font-size:18px;font-weight:bold:text")
        self.dome_button.clicked.connect(self.dome_run_func)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(os.getcwd() + "\\static\\icons\\dome_runing.png"))
        self.dome_button.setIcon(icon3)

        self.code_area = QtWidgets.QPlainTextEdit(self.layout_widget)
        self.code_area.setFont(QFont('Times', 14, QFont.Black))
        self.code_area.cursorPositionChanged.connect(self.current_line_high_light)
        self.current_line_number = None
        self.vertical_layout.addWidget(self.code_area)

        self.code_area_icon = QtWidgets.QLabel(self.main)
        self.code_area_icon.setGeometry(QtCore.QRect(370, 20, 131, 31))
        png = QtGui.QPixmap(os.getcwd() + "\\static\\icons\\code_area.png")
        self.code_area_icon.setPixmap(png)

        self.code_area_text = QtWidgets.QLabel(self.main)
        self.code_area_text.setGeometry(QtCore.QRect(430, 20, 131, 31))
        self.code_area_text.setText("生成代码片段:")
        # self.code_area_text.setStyleSheet(
        #     "color:rgb(10,10,10,255);font-size:20px;font-weight:bold;font-family:Roman times;")

        QtCore.QMetaObject.connectSlotsByName(self.main)

    def current_line_high_light(self):
        new_current_line_number = self.code_area.textCursor().blockNumber()
        if new_current_line_number != self.current_line_number:
            line_color = QColor(Qt.yellow).lighter(160)
            self.current_line_number = new_current_line_number
            hi_selection = QTextEdit.ExtraSelection()
            hi_selection.format.setBackground(line_color)
            hi_selection.format.setProperty(QTextFormat.FullWidthSelection, True)
            hi_selection.cursor = self.code_area.textCursor()
            hi_selection.cursor.clearSelection()
            self.code_area.setExtraSelections([hi_selection])

    def combo_box_event(self, i):
        # 下拉后可触发事件
        print(i)

    def pen_target_event(self):
        code_text = handle_target_tool(self.cb.currentText())
        code_text_json = json.loads(code_text)
        if code_text_json.get("result") == 'success':
            self.code_text = code_text
            self.format_code_result = format_code(code_text_json)
            self.write()
            self.notice_text.setText("抓取成功")
        else:
            self.notice_text.setText("抓取失败")
        shell = win32com.client.Dispatch("WScript.Shell")
        shell.SendKeys('^')
        win32gui.SetForegroundWindow(get_global_handle())

    def export_file(self):
        self.work_file = os.getcwd()
        directory = QFileDialog.getExistingDirectory(self.export_button, '选取文件夹', self.work_file)
        if self.code_area.toPlainText():
            with open(directory + '\\export_file.txt', 'w', encoding='utf-8') as e:
                e.write(self.code_area.toPlainText())
                e.close()

    def dome_run_func(self):
        if self.code_text and self.format_code_result and self.code_area.toPlainText():
            codes = run_dome_tool(json.loads(self.code_text), self.code_area.toPlainText())
            set_run_dome_code(codes)
        else:
            set_run_dome_code('')

    def write(self):
        """"""
        self.code_area.clear()
        cursor = self.code_area.textCursor()
        # cursor.movePosition(QtGui.QTextCursor.End)
        # cursor.insertText(self.format_code_result + "\n")   # 移动光标到最后，并追加文本
        cursor.insertText(self.format_code_result)
        self.code_area.setTextCursor(cursor)
        self.code_area.ensureCursorVisible()

    def bind_trigger(self):
        self.pen_button.clicked.connect(lambda: self.timer.start(1))


def get_main_index_body(parent):
    main_index_body = MainIndexBody(parent)
    return main_index_body


class MainIndexUi(QWidget):
    def __init__(self, parent=None):
        super(MainIndexUi, self).__init__(parent)
        self.index_ui()

    def index_ui(self):
        self.setWindowTitle("主页")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(os.getcwd() + "\\static\\icons\\main.png"))
        self.setWindowIcon(icon)
        width = 1500
        height = 800
        self.setFixedSize(width, height)
        get_main_index_body(self)
        self.create_menu()

    def create_menu(self):
        self.tray_main = QtWidgets.QWidget()
        self.tray_main.setWindowTitle("Windows Grab Tool")
        tray = QSystemTrayIcon(self.tray_main)
        tray.setToolTip("Windows Grab Tool")
        tray.setIcon(QtGui.QIcon(os.getcwd() + "\\static\\icons\\main_white.png"))

        # 主页
        index_menuitem = QAction("主页", self.tray_main, triggered=self.index_show)
        # 语言
        language_menuitem = QAction("语言", self.tray_main)
        # 版本
        version_information_menuitem = QAction("版本", self.tray_main)
        # 退出
        exit_menuitem = QAction("退出", self.tray_main, triggered=self.login_quit)
        blank_menuitem = QAction("", self.tray_main)

        # 创建菜单
        tray_menu = QMenu(self.tray_main)
        tray_menu.addAction(index_menuitem)
        tray_menu.addAction(language_menuitem)
        tray_menu.addAction(blank_menuitem)

        # 增加分割线
        tray_menu.addSeparator()
        tray_menu.addAction(version_information_menuitem)
        tray_menu.addAction(exit_menuitem)

        tray.setContextMenu(tray_menu)
        tray.show()
        tray.showMessage("Window Grab Tool", "欢迎")
        self.tray = tray

    def index_show(self):
        self.show()
        handle = win32gui.GetForegroundWindow()
        set_global_handle(handle)

    def closeEvent(self, event):
        event.ignore()
        self.hide()

    def login_quit(self):
        self.quit()
